//index.js
//获取应用实例
var app = getApp()
var util = require('../../utils/util.js')
Page({
  data: {
    from_array: util.getLanguageCode(),
    to_array: [],
    query:'',
    to_query:'',
    form_array_index: 0,
    form_to_index: 0,
    userInfo: {}
  },
  //切换from值
  bindFromChange:function(e){
    this.setData({
      form_array_index: e.detail.value
    })
  },
  //切换to值
  bindToChange: function (e) {
    this.setData({
      form_to_index: e.detail.value
    })
    this.toHttpTranslate();
  },
  //文本框失去焦点
  bindTextAreaBlur:function(e){
    this.setData({
      query: e.detail.value
    })
    this.toHttpTranslate();
  },
  //点击键盘完成事件
  confirm:function(e){
    this.setData({
      query: e.detail.value
    })
    this.toHttpTranslate();
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    console.log('onLoad')
    
    var that = this
    //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo){
      //更新数据
      var selectKey = wx.getStorageSync('selectKey');
      var toList = util.getLanguageCode();
      toList.shift()
      that.setData({
        userInfo:userInfo,
        to_array: toList,
        form_array_index: selectKey?selectKey.from_key:0,
        form_to_index: selectKey ? selectKey.to_key : 0
      })
    })
  },
  toHttpTranslate:function(){
    var that = this;
    var obj = that.data;
    if (!obj.query){
      return;
    }
    wx.showLoading({
      title: '翻译中',
    })
    wx.request({
      url: 'https://www.wangjoe.com/api4/wukong/index',
      data: {
        query: obj.query,
        from: obj.from_array[obj.form_array_index].code,
        to: obj.to_array[obj.form_to_index].code
      },
      method: 'post',
      success: function (data, statusCode, header) {
        wx.hideLoading()
        var dd = data.data;
        if (data.statusCode == 200 && dd) {
          var isSuccess = false;
          if (dd.code == 10000){
            // obj.data.trans_result.dst
            var list = dd.data.trans_result;
            if (list && list.length > 0){
              var toquery = list.map(function (v) {
                return v.dst;
              }).join('\n')
              that.setData({
                to_query: toquery
              });

              wx.setStorageSync('selectKey', {
                from_key: obj.form_array_index,
                to_key: obj.form_to_index
              })
              isSuccess = true;
            }
            
          }
          if (!isSuccess){
            wx.showToast({
              title: '服务器丢了，请稍候再试',
              icon: 'success',
              duration: 2000
            })
          }
        }
      }
    })
  }
})
